package com.senyint.sys.utils.crypto;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

public class AES {

    public static SecretKeySpec genKey(String password) throws NoSuchAlgorithmException {
        // 创建AES的Key生产者
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        // 确定密钥长度
        kg.init(128, new SecureRandom(password.getBytes()));
        byte[] keyBytes = kg.generateKey().getEncoded();
        // 转换为AES专用密钥
        return new SecretKeySpec(keyBytes, "AES");
    }

    public static String encode(String password, String content) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        // 生成创建密码器
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        // 进入加密模式
        cipher.init(Cipher.ENCRYPT_MODE, genKey(password));
        byte[] result = cipher.doFinal(content.getBytes());
        return Base64.getEncoder().encodeToString(result);
    }

    public static String decode(String password, String encodeContent) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        // 生成创建密码器
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        // 进入解密模式
        cipher.init(Cipher.DECRYPT_MODE, genKey(password));
        return new String(cipher.doFinal(Base64.getDecoder().decode(encodeContent)));
    }

    public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidKeySpecException {
        String pwd = "abc";
        String encode = AES.encode("123", pwd);
        System.out.println(encode);
        System.out.println(AES.decode("123", encode));
    }
}